package com.tianyuchan.exception.util;

import com.tianyuchan.exception.enums.CommonResponseCode;
import com.tianyuchan.exception.exception.ContractManageException;
import com.tianyuchan.exception.dto.resp.BaseResponse;
import lombok.extern.log4j.Log4j;

import java.util.Objects;
import java.util.function.Function;

/**
 * @Classname : ResponseProcessor
 * @Description : 业务异常处理类（Function接口实现）
 * @Author : cty
 * @Date 2023/3/19 20:50
 */

@Log4j
public class ResponseProcessor {

    public static <T, R extends BaseResponse> R handle(T request, R response, String method, Function<T, R> function) {
        try {
            log.info(String.format("before method = {%s}, request = {%s}", method, request));

            // requireNonNull()
            Objects.requireNonNull(request);

            // BeanVaildator.vaildateObject(request)

            response = function.apply(request);

            if (response.getCode() == null) {
                response.setCode(CommonResponseCode.SUCCESS.name());
            }

            return response;

        } catch (ContractManageException e) {
            // 记录日志
            log.error(e.getErrorMsg(), e);
            // 封装返回
            response.setSuccess(false);
            response.setCode(e.getErrorCode());
            response.setMsg(e.getErrorMsg());
        } catch (IllegalArgumentException e) {
            // 记录日志
            log.error(e.getMessage(), e);
            // 封装返回
            response.setSuccess(false);
            response.setCode(CommonResponseCode.ILLEGAL_ARGUMENT.name());
            response.setMsg(e.getMessage());
        } catch (Throwable e) {
            // 记录日志
            log.error(e.getMessage(), e);
            // 封装返回
            response.setSuccess(false);
            response.setCode(CommonResponseCode.SYSTEM_ERROR.name());
            response.setMsg(e.getMessage());
        } finally {
            log.info(String.format("after method = {%s}, request = {%s}, response = {%s}", method, request, response));
        }
        return response;
    }

}
